import json

import requests
from flask import request

from blues.cluster import bp
from config import K8s_API_PREFIX, UA
from model.cluster import Cluster
from public.time_utils import getUTCtime


# 搜素资源接口，适用于k8s里各种资源类型
@bp.route('/api/cluster/<cluster_id>/<namespace>/<res_type>/')
@bp.route('/api/cluster/<cluster_id>/<namespace>/<res_type>/<name>')
def search(cluster_id, namespace, res_type, name=''):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)
    selector = request.args.get("selector")
    print(selector)
    # 调用k8s apiserver
    if namespace == "_all":
        path_mid = ""
    else:
        path_mid = "/namespaces/" + namespace

    url = cluster['apiserver'] + K8s_API_PREFIX[res_type] + path_mid + "/" + res_type + "/" + name
    if selector:
        s_list = selector.split(",")
        url = url + "?labelSelector="
        for i in s_list:
            url = url + i + ","
        url = url.rstrip(",")
    print(url)
    headers = {"Authorization": "Bearer " + cluster['token'], "User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False)
    # print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/<type>/<resource>/restart')
def restart(cluster_id, namespace, type, resource):
    c = Cluster()
    print("ddd")
    cluster = c.find_by_id(cluster_id)

    # 获取现在的deploy资源声明
    url = cluster['apiserver'] + "/apis/apps/v1/namespaces/" + namespace + "/" + type + "/" + resource
    print(url)
    headers = {
        "Authorization": "Bearer " + cluster['token'],
        "User-Agent": UA,
        "Content-Type": "application/strategic-merge-patch+json"
    }
    data = {
        "spec": {
            "template": {
                "metadata": {
                    "annotations": {
                        "kubectl.kubernetes.io/restartedAt": getUTCtime()
                    }
                }
            }
        }
    }
    # 再使用patch方法修改原始deployment资源声明
    response = requests.patch(url=url, headers=headers, data=json.dumps(data), verify=False)
    print(response.text)
    try:
        code = response.status_code
    except Exception as e:
        print(e)
        code = 500
    if code == 200:
        return "success"
    else:
        return "failed"


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/deployment/<deployment>/update/')
def update_image_api(cluster_id, namespace, deployment):
    image = request.args.get('image')
    return update_image(cluster_id, namespace, deployment, image)


def update_image(cluster_id, namespace, deployment, image):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)

    # 获取现在的deploy资源声明
    url = cluster['apiserver'] + "/apis/apps/v1/namespaces/" + namespace + "/deployments/" + deployment
    headers = {"Authorization": "Bearer " + cluster['token'], "User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False)
    # print(response.text)
    res_dict = response.json()
    containers = res_dict["spec"]["template"]["spec"]["containers"]

    # 一个deployment里可能包括多个container，下面找到需要升级的主container对其版本号进行修改，其他容器配置声明保持不变
    # for c in containers:
    #     if c["name"] == deployment:
    #         c["image"] = image
    #         break
    containers[0]['image'] = image
    data = {
        "spec": {
            "template": {
                "spec": {
                    "containers": containers
                }
            }
        }
    }

    print(data)

    # 再使用patch方法修改原始deployment资源声明
    headers = {"Content-Type": "application/merge-patch+json", "Authorization": "Bearer " + cluster['token'],
               "User-Agent": UA}
    response = requests.patch(url=url, headers=headers, data=json.dumps(data), verify=False)
    # print(response.text)
    return response.json()


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/deployments/<name>/scale')
def read_scale(cluster_id, namespace, name):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)

    # 调用k8s apiserver
    url = cluster['apiserver'] + "/apis/apps/v1/namespaces/" + namespace + "/deployments/" + name + "/scale"
    headers = {"Authorization": "Bearer " + cluster['token'], "User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False)
    # print(response.status_code)
    # print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/deployments/<name>/scale/<replicas>')
def patch_scale(cluster_id, namespace, name, replicas):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)
    data = {
        "spec": {
            "replicas": int(replicas)
        }
    }
    # 使用patch方法修改scale
    url = cluster['apiserver'] + "/apis/apps/v1/namespaces/" + namespace + "/deployments/" + name + "/scale"
    headers = {"Content-Type": "application/merge-patch+json", "Authorization": "Bearer " + cluster['token'],
               "User-Agent": UA}
    response = requests.patch(url=url, headers=headers, data=json.dumps(data), verify=False)
    # print(response.text)
    return response.json()


if __name__ == '__main__':
    a = read_scale(100, 'default', 'nginx')
    print(a)
